<?php
namespace app\appadmin\controller\v1;
use app\admin\controller\soft\Group;
use app\app\Appbase;

//
//绩效
//
class Merits extends Appbase 
{
	/**
    * 构造函数自动执行
    * @return null
    */
    public function __construct(){
    	if( request()->identity == 3 ){
//      	return $this->ReError( '员工没有该操作权限！' );
    	}
		parent::__construct();
    }
	
	/**
	* 获取提成报表
	* /appadmin/v1/merits/tc
	* 是否需要登录 
	* @is_need_login true
	*/
	public function tc($shop_id,$month){
		//$t = 'to_days(d.add_time) = to_days(now())';

       $t = "DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('".$month."-01"."'".",'%Y%m' )";
    	try {
            $str="";
            $str.=" and shop_id=".$shop_id;

            $str_limit=" order by gh asc "."limit ".(($this->request->post('pageIndex')-1)*( $this->request->post('pageSize'))?:0).",".($this->request->post('pageSize')?:20);

            $sql=" select * from (
							select
							a.uid,a.shop_id,a.gh,a.id,a.name,
							if(b.type = 1 or b.type = 2,'服务项目','普通商品') type
							,ifnull(b.yj,0.00)+ifnull(c.yj,0.00) as yj
		 
							,(ifnull(b.service_tc,0)+IFNULL(c.ordinary_tc,0)) as tc
										
					  
							from xw_shop_staff  as a

				    	left join (

			         		select sum(i.number) as service_tc,i.uid,i.add_time,sum(pay_price) as yj,a.type  from xw_order a
									LEFT JOIN xw_user_bill i on i.link_id = a.order_no
							  	where  i.pm=1 and i.`status`=1 and i.type='rake-back' and i.category='brokerage'
										and a.is_pay=1 and a.is_del=0 and a.status>=0 and $t and a.type<>0 and a.type<>-1
									GROUP BY a.uid

			        )b  on b.uid = a.uid 
			        
							left join (

									select sum(i.number) as ordinary_tc,i.uid,i.add_time,sum(pay_price) as yj from xw_order a
									LEFT JOIN xw_user_bill i on i.link_id = a.order_no

							  	where  i.pm=1 and i.`status`=1 and i.type='rake-back' and i.category='brokerage'
										and a.is_pay=1 and a.is_del=0 and a.status>=0 and $t and a.type=0 and a.type<>-1
			            
									GROUP BY a.uid

			        )c  on c.uid = a.uid 

			        
			
                       GROUP BY gh    
			
				) a where (1=1 $str)".$str_limit;

            $tables = \Db::query($sql);

            $yj=0;
            $tc=0;
            foreach ($tables as $k=>$v){
                $yj+=$v['yj'];
                $tc+=$v['tc'];
            }

	        $total['yj'] = $yj;
	        $total['tc'] = $tc;

	        $data =  $tables;

			return $this->ReSucess( compact('total','data')  );
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}

    /**
     * 获取当前日期的前五个月
     * /appadmin/v1/merits/getLastFiveMonth
     * 需要登录
     * @is_need_login true
     */
    public function getLastFiveMonth(){
        try {

            $arr=array();
            $year=date('Y');
            $yue=date('m');
            $sign=5;
            for($i=0;$i<$sign;$i++){

                $month=mktime(0,0,0,$yue-($i+1),1,$year);
                $arr[$i]['value']=date('Y-m',$month);
                $arr[$i]['label']=date('n',$month).'月';

            }

            return $this->ReSucess($arr);
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 获取当前日期的前五个月（提成列表的显示-日期时间，包含本月）
     * /appadmin/v1/merits/getFiveMonth
     * 需要登录
     * @is_need_login true
     */
    public function getFiveMonth(){
        try {

            $arr=array();
            $year=date('Y');
            $yue=date('m');
            $sign=5;
            for($i=0;$i<$sign;$i++){

                $month=mktime(0,0,0,$yue-($i),1,$year);
                $arr[$i]['value']=date('Y-m',$month);
                $arr[$i]['label']=date('n',$month).'月';

            }

            return $this->ReSucess($arr);
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
	
	/**
	* 获取提成明细
	* /appadmin/v1/merits/tcmx
	* 是否需要登录 
	* @is_need_login true
	*/
	public function tcmx($id,$month){
        $t = "DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('".$month."-01"."'".",'%Y%m' )";
        try {
            $str="";
            $str.=" and id=".$id;

            $str_limit=" order by gh asc "."limit ".(($this->request->post('pageIndex')-1)*( $this->request->post('pageSize'))?:0).",".($this->request->post('pageSize')?:20);

            $sql=" select * from (
										select
										a.uid,a.shop_id,a.gh,a.id,a.name,
										if(c.type = 1 or c.type = 2,'服务项目','普通商品') type
						                ,ifnull(TRUNCATE(c.yj,2),0.00) as yj
										,ifnull(TRUNCATE(c.tc,2),0.00) as tc
										
							from xw_shop_staff  as a

							left join (

									select sum(i.number) as tc,i.uid,i.add_time,sum(pay_price) as yj,a.type from xw_order a
									LEFT JOIN xw_user_bill i on i.link_id = a.order_no

							  	where  i.pm=1 and i.`status`=1 and i.type='rake-back' and i.category='brokerage'
										and a.is_pay=1 and a.is_del=0 and a.status>=0 and DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('2021-07-01','%Y%m' ) and a.type<>0 and a.type<>-1
			            
									GROUP BY a.uid

			        )c  on c.uid = a.uid 
					GROUP BY gh    
 
				) a where (1=1 $str)".$str_limit;

            $sql2=" select * from (
										select
										a.uid,a.shop_id,a.gh,a.id,a.name,
										if(c.type = 1 or c.type = 2,'服务项目','普通商品') type
						                ,ifnull(TRUNCATE(c.yj,2),0.00) as yj
										,ifnull(TRUNCATE(c.tc,2),0.00) as tc
										
							from xw_shop_staff  as a

							left join (

									select sum(i.number) as tc,i.uid,i.add_time,sum(pay_price) as yj,a.type from xw_order a
									LEFT JOIN xw_user_bill i on i.link_id = a.order_no

							  	where  i.pm=1 and i.`status`=1 and i.type='rake-back' and i.category='brokerage'
										and a.is_pay=1 and a.is_del=0 and a.status>=0 and DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('2021-07-01','%Y%m' ) and a.type=0 and a.type<>-1
			            
									GROUP BY a.uid

			        )c  on c.uid = a.uid 
					GROUP BY gh    
 
				) a where (1=1 $str)".$str_limit;


            $tables_s = \Db::query($sql);
            $tables_o = \Db::query($sql2);
            $result_array= array_merge($tables_s,$tables_o);

            $yj=0;
            $tc=0;
            foreach ($result_array as $k=>$v){
                $yj+=$v['yj'];
                $tc+=$v['tc'];
            }

            $total['yj'] = $yj;
            $total['tc'] = $tc;

            $data = $result_array;


            return $this->ReSucess( compact('total','data')  );


        } catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	
	/**
	* 获取工资报表
	* /appadmin/v1/merits/gz
	* 是否需要登录 
	* @is_need_login true
	*/
	public function gz($shop_id,$month){
		try {
			//$month = date('Y-m',strtotime("-1 month"));

	        $model = model('shop_staff')->alias('a')
	        	->leftJoin('shop_staff_wages b',"a.id = b.staff_id and b.months = '".$month."'")
	        	->where('a.shop_id',$shop_id)
	        	->where('a.status',1)
	        	->where('a.is_del',0)
	        	->field("a.id,a.base_pay as dx, a.gh,a.name,a.phone,a.work_type")
	        	->field("ifnull(b.total_wages,0) as gz");
	       
	        
	       	$total['dx'] =  $model->sum('a.base_pay');	
	        $total['gz'] =  $model->sum('b.total_wages');	
	        	
	        $data =  $model->page(input('pageIndex') ?: 1,input('pageSize') ?: 20)->select();

	        	
			return $this->ReSucess( compact('total','data')  );		
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
	
	/**
	* 获取工资报表
	* /appadmin/v1/merits/gzmx
	* 是否需要登录 
	* @is_need_login true
	*/
	public function gzmx($id,$month){
		try {
			//$month = date('Y-m',strtotime("-1 month"));
			$wages = model('shop_staff_wages')->where('months',$month)->where('staff_id',$id)->find();

	        $data = [];
	        $data[] = [
	        	'type'=>'基本工资',
	        	'tc'=>number_format($wages->base_pay,2),
	        ];
	        $data[] = [
	        	'type'=>'保底业绩',
	        	'tc'=> number_format($wages->base_yj,2),
	        ];
	         $data[] = [
	        	'type'=>'业绩',
	        	'tc'=> number_format($wages->get_yj,'2'),
	        ];
	        $data[] = [
	        	'type'=>'考勤',
	        	'tc'=>number_format($wages->attendance,2),
	        ];
	        $data[] = [
	        	'type'=>'服务项目提成',
	        	'tc'=>number_format($wages->service_tc,2),
	        ];
	        $data[] = [
	        	'type'=>'普通项目提成',
	        	'tc'=>number_format($wages->ordinary_tc,2),
	        ];
//	        $data[] = [
//	        	'type'=>'线上提成',
//	        	'tc'=>$wages->online_tc,
//	        ];
//	        $data[] = [
//	        	'type'=>'其他工资合计',
//	        	'tc'=> $wages->other_sum_wages,
//	        ];
            foreach ($wages->other_wages as $k=>$v){
                $data[] = [
                    'type'=>$v['other_staff'],
                    'tc'=>number_format($v['money'],2),
                ];
            }

	       	$total['tc'] =number_format(array_sum( array_column($data, 'tc') ),2);
	        	
			return $this->ReSucess( compact('total','data')  );		
			
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}
	
}



